package org.hiucung.hlsdownloader.database

import androidx.room.TypeConverter
import org.hiucung.hlsdownloader.bean.M3U8TaskState

// 类型转换器
class M3U8TaskStateConverters {
    @TypeConverter
    fun fromM3UTaskState(state: M3U8TaskState): String {
        return when (state) {
            is M3U8TaskState.WaitingDownload -> "waiting_download"
            is M3U8TaskState.Downloading -> "downloading:${state.current}:${state.total}:${state.currentUrl}"
            is M3U8TaskState.DownloadCompleted -> "download_completed:${state.downloadedFiles.joinToString("|")}"
            is M3U8TaskState.WaitingMerge -> "waiting_merge"
            is M3U8TaskState.Merging -> "merging:${state.current}:${state.total}"
            is M3U8TaskState.MergeCompleted -> "merge_completed:${state.outFilePath}"
            is M3U8TaskState.Error -> "error:${state.message}"
        }
    }

    @TypeConverter
    fun toM3UTaskState(value: String): M3U8TaskState {
        return when {
            value == "waiting_download" -> M3U8TaskState.WaitingDownload
            value == "waiting_merge" -> M3U8TaskState.WaitingMerge
            value.startsWith("downloading:") -> {
                val parts = value.split(":")
                M3U8TaskState.Downloading(
                    current = parts[1].toInt(),
                    total = parts[2].toInt(),
                    currentUrl = parts[3]
                )
            }
            value.startsWith("download_completed:") -> {
                val files = value.removePrefix("download_completed:").split("|")
                M3U8TaskState.DownloadCompleted(files)
            }
            value.startsWith("merging:") -> {
                val parts = value.split(":")
                M3U8TaskState.Merging(
                    current = parts[1].toInt(),
                    total = parts[2].toInt()
                )
            }
            value.startsWith("merge_completed:") -> {
                M3U8TaskState.MergeCompleted(value.removePrefix("merge_completed:"))
            }
            value.startsWith("error:") -> {
                M3U8TaskState.Error(value.removePrefix("error:"))
            }
            else -> M3U8TaskState.Error("未知状态")
        }
    }
}